package com.sluggard.common.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Map;

@Slf4j
public class FreeMarkers {

	/**
	 * 渲染模板字符串。
	 */
	public static String rendereString(String templateString, Map<?, ?> model) {
		try {
			StringWriter result = new StringWriter();
			Template t = new Template("name", new StringReader(templateString), new Configuration(Configuration.VERSION_2_3_31));
			t.process(model, result);
			return result.toString();
		} catch (Exception e) {
			log.error("渲染模板字符串", e);
		}
		return "";
	}

	/**
	 * 渲染Template文件.
	 */
	public static String renderTemplate(Template template, Object model) {
		try {
			StringWriter result = new StringWriter();
			template.process(model, result);
			return result.toString();
		} catch (Exception e) {
			log.error("渲染Template文件", e);
		}
		return "";
	}

	public static String renderTemplate(Template template, Map<String, ?> model) {
		try {
			StringWriter result = new StringWriter();
			template.process(model, result);
			return result.toString();
		} catch (Exception e) {
			log.error("渲染Template文件", e);
		}
		return "";
	}

	/**
	 * 创建默认配置，设定模板目录.
	 */
	public static Configuration buildConfiguration(String directory) throws IOException {
		Configuration cfg = new Configuration(Configuration.VERSION_2_3_31);
		Resource path = new DefaultResourceLoader().getResource(directory);
		cfg.setDirectoryForTemplateLoading(path.getFile());
		return cfg;
	}

	public static String renderTemplate(String encoding, String dir, String name, Object model) {
		try {
			Configuration cfg = new Configuration(Configuration.VERSION_2_3_31);
			cfg.setDefaultEncoding(encoding);
			cfg.setClassForTemplateLoading(FreeMarkers.class, dir);
			Template t = cfg.getTemplate(name);
			return FreeMarkers.renderTemplate(t, model);
		} catch (Exception ignored) {
		}
		return "";
	}

	public static String renderTemplate(String name, Object model) {
		return renderTemplate("utf-8", "/template", name + ".ftl", model);
	}

	public static String renderTemplate(String dir, String name, Object model) {
		return renderTemplate("utf-8", dir, name + ".ftl", model);
	}
}
